﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Security;
using He.Common;
using LitJson;

namespace He.API.WeiXin
{
    public class CheckSignature
    {
        /// <summary>
        /// 验证信息
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static bool Check(string signature, string timestamp, string nonce, string token)
        {
            return (signature == GetSignature(timestamp, nonce, token));
        }

        public static string GetSignature(string timestamp, string nonce, string token)
        {
            string[] array = new string[] { token, timestamp, nonce };
            Array.Sort<string>(array);
            return FormsAuthentication.HashPasswordForStoringInConfigFile(string.Join("", array), "SHA1").ToLower();
        }

        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <returns></returns>
        public static string GetAccessToken()
        {
            string access_token = Config.wx_config.access_token;
            if (DateTime.Compare(DateTime.Now, Config.wx_config.access_token_expires_in) > 0 || string.IsNullOrEmpty(access_token))
            {
                string result = HttpHelper.HttpGet(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", Config.wx_config.appid, Config.wx_config.appsecret));
                if (result.Contains("errcode"))
                {
                    return null;
                }
                try
                {
                    Dictionary<string, object> dic = JsonMapper.ToObject<Dictionary<string, object>>(result);
                    access_token = dic["access_token"].ToString();
                    int expires_in = Convert.ToInt32(dic["expires_in"]);
                    Config.wx_config.access_token = access_token;
                    Config.wx_config.access_token_expires_in = DateTime.Now.AddSeconds((double)expires_in);
                    new BLL.config().SaveConfig<Model.wx_config>(Config.wx_config, SysKeys.WEIXIN_CONFIG_PATH);
                    return access_token;
                }
                catch
                {
                    return null;
                }
            }
            else
            {
                return access_token;
            }
        }
    }
}
